package cn.jisol.ngame.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventDispatcher {
    private static EventDispatcher instance;
    private final Map<String, List<EventListener>> listeners;

    private EventDispatcher() {
        listeners = new HashMap<>();
    }

    public static synchronized EventDispatcher getInstance() {
        if (instance == null) {
            instance = new EventDispatcher();
        }
        return instance;
    }

    public void addListener(String key, EventListener listener) {
        List<EventListener> eventListeners = listeners.computeIfAbsent(key, k -> new ArrayList<>());
        eventListeners.add(listener);
    }

    public void removeListener(String key, EventListener listener) {
        List<EventListener> eventListeners = listeners.get(key);
        if (eventListeners != null) {
            eventListeners.remove(listener);
            if (eventListeners.isEmpty()) {
                listeners.remove(key);
            }
        }
    }

    public void dispatchEvent(String key) {
        dispatchEvent(key, createDefaultEvent());
    }

    public void dispatchEvent(String key, Event event) {
        List<EventListener> eventListeners = listeners.get(key);
        if (eventListeners != null) {
            for (EventListener listener : eventListeners) {
                listener.onEvent(event);
            }
        }
    }

    private Event createDefaultEvent() {
        return new Event("Default Event");
    }

    public interface EventListener {
        void onEvent(Event event);
    }

    public static class Event {
        private final String name;

        public Event(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}

